/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tr.com.argela.tap.mot.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import tr.com.argela.tap.mot.dao.AuthenticationDao;
import tr.com.argela.tap.mot.dao.DbManager;
import tr.com.argela.tap.mot.dao.ProjectDao;
import tr.com.argela.tap.mot.dao.VersionDao;
import tr.com.argela.tap.mot.logger.LoggerFactory;
import tr.com.argela.tap.mot.models.Project;
import tr.com.argela.tap.mot.models.User;
import tr.com.argela.tap.mot.models.Version;

/**
 * @author arge
 */
public class ProjectServlet extends HttpServlet {

    /**
	 * 
	 */
    private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger("servlets");

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (request.getParameter("project") != null) {
            if (request.getParameter("project").equals("projectsproperties")) {

                projectsproperties(request, response);
            } else if (request.getParameter("project").equals("createproject")) {
                createProject(request, response);
            } else if (request.getParameter("project").equals("updateproject")) {
                updateProject(request, response);
            }
        }

        if (request.getParameter("page") != null) {
            if (request.getParameter("page").equals("project")) {
                getVersionsOfProject(request, response);
            }
        }

    }

    private void getVersionsOfProject(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            String projectId = request.getParameter("getVersionsOfProject");
            VersionDao versionDao = new VersionDao();
            List<Version> versionList = versionDao.seethisVersions(Long.parseLong(projectId));
            String result = "";

            for (Version version : versionList) {
                result += version.getId() + ";" + version.getName() + "#";
            }

            response.getWriter().write(result);
        } catch (Exception e) {
            logger.error("Error in getting versions", e);
        }

    }

    public void updateProject(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("Process request called");
        DbManager dbManager = new DbManager();

        try {
            ProjectDao proDao = new ProjectDao();
            String projectName = request.getParameter("projectname");
            String projectDescription = request.getParameter("prodescription");
            User user = (User) request.getSession().getAttribute("userObject");
            Long projectId = Long.parseLong(request.getParameter("projectId"));

            System.out.print("Project details" + projectName + " " + projectDescription);
            int result = proDao.updateProject(dbManager, projectName, user, projectDescription, projectId);
            Project project = null;
            if (result > 0) {
                project = new Project();
                project.setName(projectName);
                project.setDescription(projectDescription);
                AuthenticationDao autDao = new AuthenticationDao();
                user = autDao.getUserById(user.getId());
                project.setUser(user);
            }
            request.getSession().setAttribute("project", project);

            dbManager.commit();
        } catch (Exception e) {
            dbManager.rollback();
        } finally {
            dbManager.close();
        }
        response.sendRedirect("newprojectproperties.jsp");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    public void projectsproperties(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("Process request called");

        DbManager dbManager = new DbManager();
        try {
            if (request.getParameter("id") == null)
                response.sendRedirect("currentProjects.jsp");

            ProjectDao projectdao = new ProjectDao();
            Long proid = Long.parseLong((String) request.getParameter("id"));
            System.out.print("Gelen project" + proid);
            Project project = projectdao.checkproject(proid);
            if (project != null) {
                request.getSession().setAttribute("projectObject", project);
            }
            dbManager.commit();
        } catch (Exception e) {
            dbManager.rollback();
        } finally {
            dbManager.close();
        }
        response.sendRedirect("properties.jsp");

    }

    /**
     * Returns a short description of the servlet.
     * 
     * @return a String containing servlet description
     */

    public void createProject(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        logger.info("Process request called");
        DbManager dbManager = new DbManager();

        try {
            ProjectDao proDao = new ProjectDao();
            String projectName = request.getParameter("pname");
            String projectDescription = request.getParameter("pdescription");
            User user = (User) request.getSession().getAttribute("userObject");

            System.out.print("Project details" + projectName + " " + projectDescription);
            int result = proDao.addProject(dbManager, projectName, user, projectDescription);
            Project project = null;
            if (result > 0) {
                project = new Project();
                project.setName(projectName);
                project.setDescription(projectDescription);
                AuthenticationDao autDao = new AuthenticationDao();
                user = autDao.getUserById(user.getId());
                project.setUser(user);
            }
            request.getSession().setAttribute("project", project);
            dbManager.commit();
        } catch (Exception e) {
            dbManager.rollback();
        } finally {
            dbManager.close();
        }
        response.sendRedirect("newprojectproperties.jsp");
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
